<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?
	// Logeo de facebook
	$app_id = "	177160209074782";
	$app_secret = "	d29e1578d98135678f119c1cd1c62bf6";
	$canvas_page = "https://apps.facebook.com/thefiubalatexproject/";
	
	$auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page);
	//&scope=email,read_stream
	
	$signed_request = $_REQUEST["signed_request"];
	
	list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
	
	$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
	$extraData = null;
	
	if (empty($data["user_id"])) {
		// if its logged
		echo("<script> top.location.href='" . $auth_url . "'</script>");
	} else {
		// if its not
		
		$jsonExtraData = file_get_contents("https://graph.facebook.com/".$data['user_id']);
		$extraData = json_decode( $jsonExtraData );
		
		include('dbcon.php');
		mysql_query("REPLACE INTO users (last_ip, userid, name, last_date) VALUES('".$_SERVER['REMOTE_ADDR']."', '".$data['user_id']."', '".($extraData->first_name)." ".($extraData->last_name)."','".strtotime(date("Y-m-d H:i:s"))."')");
	}
	
	// print_r($data);
	// print_r($extraData);
?>
	
<html>


<head>
<title>Muro</title>

<!-- Load tabs library stuff-->
	<script type="text/javascript" src="libreriasJavascript/cookiesTabber.js"></script>
	<script type="text/javascript" src="libreriasJavascript/tabber.js"></script>
	<link rel="stylesheet" href="dependencies/example.css" TYPE="text/css" MEDIA="screen">
	<link rel="stylesheet" href="dependencies/example-print.css" TYPE="text/css" MEDIA="print">
<!-- End loading tabs library-->

<link href="facebox.css" media="screen" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="indexjs.js"></script>
<script type="text/javascript" src="jquery.livequery.js"></script>
<link href="dependencies/screen.css" type="text/css" rel="stylesheet" />

<script src="jquery.elastic.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.watermarkinput.js" type="text/javascript"></script>

<script type="text/javascript">
	var chatTableName = -1;
	var lastDateChat = -1;
	var lastMessageGet = -1;
	
	// the value of timeWaitedIntervals[n] is used when the time elapsed since the last response was beetween timeWaitedRefresh[n] and timeWaitedRefresh[n + 1]
	var timeWaitedRefresh = 	new Array(0, 15, 45, 90, 180, 360, 600, 1200, 2700, 99999999)	// seconds
	var timeWaitedIntervals = 	new Array(4, 3.5, 6, 10, 15, 30, 60, 90, 120);	
	var lastState = 0;
	
	setInterval(function(){ checkNewChat(); }, 30000);	// in miliseconds
	var refreshChatInterval = setInterval(function(){ refreshChat(); }, timeWaitedIntervals[0] * 1000);	// in miliseconds
	
	
	function refreshChat()
	{
		if (chatTableName != "-1")
		{
			loadPreviousChat();
		}
		
		if (lastMessageGet != -1)
		{
			var timeVal = Math.round((new Date()).getTime() / 1000) - lastMessageGet;
			var i = 0;
			
			while (timeWaitedRefresh[i + 1] < timeVal) {
				i++;
			}
			
			if (lastState != i)
			{
				lastState = i;
				window.clearInterval(refreshChatInterval);
				refreshChatInterval = setInterval(function(){ refreshChat(); }, timeWaitedIntervals[i] * 1000);
			}
		}
	}
	
	$(document).ready(function(){	
		
		checkNewChat();
	
	
		function submitPost(){
			var a = $("#watermark").val();
				if(a != "What's on your mind?")
				{
					$.post("posts.php?value="+a+"&user_id=<?echo $data['user_id'];?>&fname=<?echo $extraData->first_name;?>&lname=<?echo $extraData->last_name;?>", {
		
					}, function(response){
						
						$('#posting').prepend($(response).fadeIn('slow'));
						$("#watermark").val("What's on your mind?");
					});
				}
			
		}
		// SubmitPost
		$('#shareButton').click(function(){
			submitPost();	
		});	
	
		// SubmitPost (enter)
		$('#watermark').livequery("keydown", function(e) {
			if (e.keyCode == 13){
				e.preventDefault();
				submitPost();
			}	
		});
		
		
		// SubmitChat
		$('#chatButton').click(function(){
			submitChat();
		});	
		
		
		// SubmitChat (enter)
		$('#chatWatermark').livequery("keydown", function(e) {
			if (e.keyCode == 13){
				e.preventDefault();
				submitChat();
			}
		});
		
		function submitChat()
		{
			var a = $("#chatWatermark").val();
			if(a != "" && chatTableName != -1) // If there is something written and has selected a person
			{
				$("#chatWatermark").val("");
				$.post("chat.php?value="+a+"&user_id=<?echo $data['user_id'];?>&chatTableName="+chatTableName, {
				}, function(response){
					
					$('#postingChat').append($(response));
					
					var elem = document.getElementById('postingChatContainer');
					elem.scrollTop = elem.scrollHeight;
				});
			} else if (chatTableName == -1) {
				alert("Primero debes seleccionar un amigo con quien chatear!");
			}
		}
		
		function submitComment(getpID,comment_text){
			if(comment_text != "Write a comment...")
			{
				$.post("add_comment.php?comment_text="+comment_text+"&post_id="+getpID+"&user_id=<?echo $data['user_id'];?>&fname=<?echo $extraData->first_name;?>&lname=<?echo $extraData->last_name;?>", {
				}, function(response){
					
					$('#CommentPosted'+getpID).append($(response).fadeIn('slow'));
					$("#commentMark-"+getpID).val("Write a comment...");					
				});
			}
			
		
		}
		//SubmitComment (click)
		$('a.comment').livequery("click", function(e){
			var getpID =  $(this).parent().attr('id').replace('commentBox-','');	
			var comment_text = $("#commentMark-"+getpID).val();
			submitComment(getpID,comment_text);			
		});	
		
		
		// SubmitComment (enter)
		$('.commentMark').livequery("keydown", function(e) {
			if (e.keyCode == 13){
				e.preventDefault();
				var temp =  $(this).attr('id').replace('commentBox-','');	
				var getpID = temp.replace('commentMark-','');
				var comment_text = $("#commentMark-"+getpID).val();	
				submitComment(getpID,comment_text);
			}	
		});
		
});
	
	function isNumber(character)
	{
		var numbers = "0123456789";
		
		for (var i = 0; i < 10; i++)
		{
			if (character == numbers.charAt(i)) return true;
		}
		
		return false;
	}
	
	function getNumber(_string)
	{
		toReturn = _string;
		
		for(var i = 0; i < toReturn.length; i++)
		{
			if (isNumber(toReturn.charAt(i)) == false)
			{
				toReturn = toReturn.slice(0, i);
				break;
			}
		}
		
		if (toReturn == "" || isNumber(toReturn.charAt(0)) == false)
		{
			return "-1";
		} else {
			return toReturn;
		}
	}
	
	function checkNewChat()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		} else {// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				
				var chatTable = getNumber(xmlhttp.responseText);
				
				if (chatTable != "-1")
				{
					chatTableName = chatTable;
					loadPreviousChat();
				}
			}
		}
		
		xmlhttp.open("GET","chatQuery.php?to_id=-1&user_id=<? echo $data['user_id']; ?>", true);
		xmlhttp.send();

	}
	
	function startChat( idToChat, nameToChat ) {
		document.getElementById('postingChat').innerHTML = "";
		lastDateChat = -1;
		lastMessageGet = -1;
		
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		} else {// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				chatTableName = getNumber(xmlhttp.responseText);
				loadPreviousChat(); // White if there wasnt any chat before
			}
		}
		
		xmlhttp.open("GET","chatQuery.php?to_id="+idToChat+"&user_id=<? echo $data['user_id']; ?>", true);
		xmlhttp.send();
		
		document.getElementById("person1Img").src = "https://graph.facebook.com/"+idToChat+"/picture";
		document.getElementById("person1Name").innerHTML = nameToChat;
		document.getElementById("person1").style.visibility = "visible";
	}
	
	function loadPreviousChat()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		} else {// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				if (xmlhttp.responseText.charCodeAt(0) != 13 || xmlhttp.responseText.charCodeAt(1) != 10) // No content
				{
					document.getElementById('postingChat').innerHTML += xmlhttp.responseText;
					
					var elem = document.getElementById('postingChatContainer');
					elem.scrollTop = elem.scrollHeight;
					
					lastMessageGet = Math.round((new Date()).getTime() / 1000);
				}
			}
		}
		
		xmlhttp.open("GET","getPreviousChat.php?getFirstsMessagges=false&chatTableName="+chatTableName+"&last_date="+lastDateChat+"&user_id="+<? echo $data['user_id']; ?>, true);
		
		lastDateChat = Math.round((new Date()).getTime() / 1000);
		
		xmlhttp.send();
	}
	
	function loadMoreChatMessages()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		} else {// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		// If there are more that one element with the same id, getElementById returns the first it appears.
		var firstDateChat = document.getElementById('first_date').innerHTML;
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				if (xmlhttp.responseText.charCodeAt(0) != 13 || xmlhttp.responseText.charCodeAt(1) != 10) // If there is some content
				{
					document.getElementById('showMoreChatsBefore'+firstDateChat).style.visibility = "hidden";
					
					var temp = xmlhttp.responseText;
					temp += document.getElementById('postingChat').innerHTML;
					document.getElementById('postingChat').innerHTML = temp;
					
					// If there are more that one element with the same id, getElementById returns the first it appears.
					firstDateChat = document.getElementById('first_date').innerHTML;
				}
			}
		}
		
		xmlhttp.open("GET","getPreviousChat.php?getFirstsMessagges=true&chatTableName="+chatTableName+"&first_date="+firstDateChat+"&user_id="+<? echo $data['user_id']; ?>, true);		
		xmlhttp.send();
	}
	

	
</script>

<script type="text/javascript">

/* Optional: Temporarily hide the "tabber" class so it does not "flash"
   on the page as plain HTML. After tabber runs, the class is changed
   to "tabberlive" and it will appear. */

document.write('<style type="text/css">.tabber{display:none;}<\/style>');
</script>




</head>

<!-- Facebook resizing and send request shit-->

<script src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
	window.fbAsyncInit = function() {
		FB.init({
		appId : '177160209074782',
		status : true, // check login status
		cookie : true, // enable cookies to allow the server to access the session
		xfbml : true // parse XFBML
		});
	
		FB.Canvas.setAutoGrow();
	}

	(function(d, debug){
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) {return;}
	js = d.createElement('script'); js.id = id; js.async = true;
	js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
	ref.parentNode.insertBefore(js, ref);
	}(document, /*debug*/ false));
	
	function sendRequestViaMultiFriendSelector() {
		FB.ui({method: 'apprequests',
			message: '¿Quieres entrar al grupo fiuba?'
		}, requestCallback);
	}
	
	function requestCallback(response) {
		// Handle callback here
	}
</script>

<!-- End Facebook resizing and send request shit-->	


<body>
<div class="tabber" align = "left" style="border:0px;">
	<div class="tabbertab" title="Muro tipo grupo FIUBA" align = "center" id="wallTab">
		<!-- Muro 	-->
		<img src="imagen_Project.png" style="float:center;" alt="" />

			<div align="center">
			<a id="invite" style="float:center" class="small button Invite" onClick="sendRequestViaMultiFriendSelector();" > Invita a un amigo! </a> 
			</div>
			<br>
			<div align="center">
			
				<form action="" method="post" name="postForm">
			
				<div class="UIComposer_Box">
			
				<span class="w">
				<textarea class="input" id="watermark" name="watermark" style="height:40px" cols="60"></textarea>
				</span>
			
					<br clear="all" />
					
					<div align="left" style="height:30px; padding:10px 5px;">
						
		<!--
						<span style="float:left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						&nbsp;
						</span>
		-->
						<a id="shareButton" style="float:left" class="small button Detail"> Share</a>
			
					</div>
			
				</div>
			
				</form>
			
				<br clear="all" />
			
				<div id="posting" align="center">
			
				<?php
					include('dbcon.php');
					include_once('posts.php');
				?>
				
				</div>
			</div>
			

		<br clear="all" /><br clear="all" /><br clear="all" /><br clear="all" />
	</div>
	
	<!-- Chat -->
	<div class="tabbertab" title="Chat" style="border:0px;" id="chatTab">
		
		<table border="2">
			<tr>
			<td> <!-- List of friend to chat with -->
				<div style="height:500px;width:240px;border:0px solid #ccc; position:relative;top:0px;left:0px;">
					<titleChat>Usuarios disponibles</titleChat><br><br><br>
					<?php
						include('dbcon.php');
						$result = mysql_query("SELECT * FROM users");
						
						if ( mysql_errno($link) != 0 )
						{
							mysql_query("INSERT INTO errors (errno, error, date_created) VALUES('".mysql_errno($link)."', '".mysql_error($link)."', '".strtotime(date("Y-m-d H:i:s"))."')");
						}
						
						for ($i = 0; $i < mysql_num_rows($result); $i++ )
						{
					?>
							<a onclick="startChat(<? echo mysql_result($result, $i, 'userid'); ?>, '<? echo mysql_result($result, $i, 'name'); ?>');">
								
								<table border='0'>
									<td>
										<img src="https://graph.facebook.com/<? echo mysql_result($result, $i, 'userid'); ?>/picture" width="40" style="float:left;" />
									</td>
									<td>
										<p class="name"> <? echo '<b>'.mysql_result($result, $i, 'name').'</b>'; ?> </p>
									</td>
								</table>
							</a>
					<?php
						}
						
					?>
					
				</div>
			</td>
			<th rowspan="2" style="width:100px;"> </th>
			<td> 
			<!-- chat screen -->
			<div align="right" style="border:0px;">
				<div id="postingChatContainer" style="height:500px;width:730px;border:0px solid #ccc;position:relative;overflow-y:scroll;overflow-x:hidden;">
					
					<br clear="all" />
					
					<div id="postingChat" align="left" >
					<?php
						include('dbcon.php');
						include_once('posts.php');
					?>
					</div>
				</div>
			</div>
			</td>
			</tr>
			<tr>
				<td >
					<p><b> Personas con las que estas hablando: </b></p>
					<div style="height:50px;overflow-y:scroll;overflow-x:hidden;border:0px solid #ccc; position:relative;top:0px;left:0px;"> 
							<div id="person1" style="visibility: hidden">
							<table border='0'>
								<td>
									<img id="person1Img" src="" width="40" style="float:left;" />
								</td>
								<td>
									<p id="person1Name"> </p>
								</td>
							</table>
						</div>
						
					</div>
				</td>
				<td>
					<form action="" method="post" name="postForm" >
				
					<div class="UIComposer_Box_Chat" style="border:0px" >
				
					<span class="w">
					<textarea class="input" id="chatWatermark" name="watermark" style="height:40px" cols="60"></textarea>
					</span>
				
						<br clear="all" />
						
						<div align="left" style="height:30px; padding:10px 5px;">
							
							<a id="chatButton" style="float:left" class="small button Chat"> Hablar </a>
							
						</div>
				
					</div>
				
					</form>
				</td>
			</tr>
			
		</table>

		<br clear="all" /><br clear="all" /><br clear="all" /><br clear="all" />
		
	</div>
	
	<div class="tabbertab" title="Grupos" style="border:0px;">
	</div>
	
	<div class="tabbertab" title="Archivos" style="border:0px;">
	</div>
	
	
</div>
			  
</body>

</html>

